﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
using System.Linq;
using ViewModel.Response;

namespace Management.Filters
{
    public class ValidateModelFilter : IActionFilter
    {
        public int Order { get; set; } = int.MaxValue - 10;
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var result = new ResponseModel<IEnumerable<object>>
                {
                    Data = context.ModelState.Keys.Select(x =>
                        new
                        {
                            Key = x,
                            Errors = context.ModelState[x].Errors.Select(e => e.ErrorMessage)
                        }),
                    Status = ResponseStatus.ValidModel,
                };
                context.Result = new OkObjectResult(result);
            }
        }
    }
}
